package com.chuangtie.tlcms.saturn.infrastructure.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chuangtie.secondary.lining.common.exception.OpenException;
import com.chuangtie.secondary.lining.common.response.OpenResponseCode;
import com.chuangtie.secondary.lining.common.util.copy.BeanCopyUtil;
import com.chuangtie.tlcms.saturn.domain.aggregate.Property;
import com.chuangtie.tlcms.saturn.domain.aggregate.PropertyInfo;
import com.chuangtie.tlcms.saturn.domain.aggregate.PropertyQuery;
import com.chuangtie.tlcms.saturn.domain.repository.PropertyRepository;
import com.chuangtie.tlcms.saturn.infrastructure.dao.entity.PropertyDO;
import com.chuangtie.tlcms.saturn.infrastructure.dao.mapper.PropertyMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @Author: 廖智威
 * @CreateTime: 2024-07-09
 */
@Repository
@RequiredArgsConstructor
public class PropertyRepositoryImpl implements PropertyRepository {

    private final PropertyMapper propertyMapper;

    /**
     * 获取工程列表
     * @return
     */
    @Override
    public List<PropertyInfo> propertyInfoList(PropertyQuery propertyQuery) {
        List<PropertyDO> propertyDOList = propertyMapper.selectList(new LambdaQueryWrapper<PropertyDO>().orderByDesc(PropertyDO::getCreateTime));
        if (!CollectionUtils.isEmpty(propertyDOList)) {
            return BeanCopyUtil.copyListToList(propertyDOList, PropertyInfo.class);
        }
        return Collections.emptyList();
    }

    /**
     * 创建工程
     * @param property
     * @return
     */
    @Override
    public Boolean createProperty(Property property) {
        PropertyDO propertyDO = propertyMapper.selectOne(new LambdaQueryWrapper<PropertyDO>().eq(PropertyDO::getName, property.getName()));
        if (Objects.nonNull(propertyDO)) {
            throw new OpenException(OpenResponseCode.PROPERTY_NAME_EXIT);
        }
        return propertyMapper.insert(BeanCopyUtil.copy(property, PropertyDO.class)) > 0;
    }
}
